﻿using _111.Models;
using _111.QywxDocument.DigitalizationDemand.Model;
using _111.QywxDocument.MeiTuanComment.Model;
using _111.QywxDocument.Model;
using _111.QywxDocument.WeeklyReport.Model;
using guidHelper;
using MyDapperApi.Models;
using MyDapperApi.Services.QywxBase;
using Newtonsoft.Json;
using QYWXUpdate.DataModel;
using QYWXUpdate.DataModel.QYWXDocument;
using System;
using static MyDapperApi.Services.DateBaseService;

namespace MyDapperApi.Services.QywxDocument.WeeklyReport;
public class DocWeeklyReportService : IDocWeeklyReportService
{
    private readonly IConfiguration _configuration;
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly IDateBaseService _dateBaseService;
    private readonly IQywxBaseService _qywxBaseService;
    public readonly ICsvService _csvService;
    private readonly string _qywxReceiveToken = "sdas";
    private readonly INetUpdateService _netUpdateService;
    private readonly INetDocumentService _netDocumentService;

    public DocWeeklyReportService(IHttpClientFactory httpClientFactory,
        IConfiguration configuration,
        IDateBaseService dateBaseService,
        ICsvService csvService,
        IQywxBaseService qywxBaseService,
        INetUpdateService netUpdateService,
        INetDocumentService netDocumentService)
    {
        _configuration = configuration;
        _httpClientFactory = httpClientFactory;
        _dateBaseService = dateBaseService;
        _csvService = csvService;
        _qywxBaseService = qywxBaseService;
        _netUpdateService = netUpdateService;
        _netDocumentService = netDocumentService;
    }

    #region 拉取企业微信汇报表格-》数据库
    /// <summary>
    /// 拉取一定时间内汇报并更新入数据库
    /// </summary>
    /// <param name="offset"></param>
    /// <param name="limit"></param>
    /// <returns></returns>
    public async Task<CommonResponse> UpdateDataBaseWeeklyReport(UpdateDocumentRequest request)
    {
        var result = new CommonResponse();
        var endTime = DateTime.Now;
        if (request.dateTime.HasValue)
        {
            endTime = request.dateTime.Value;
        }
        var startTime = endTime.AddHours(-0.5);

        var content1 = new
        {
            starttime = ToolHelper.LocalTimeToTimestampSeconds(startTime),
            endtime = ToolHelper.LocalTimeToTimestampSeconds(endTime),
            cursor = request.cursor,
            limit = request.limit
        };
        var temp = JsonConvert.SerializeObject(content1);

        var content = new StringContent(
            JsonConvert.SerializeObject(content1),
            System.Text.Encoding.UTF8,
            "application/json");

        var wxResponse = await _qywxBaseService.QywxCommonPost<UpdateDocumentResponse>(content, "https://qyapi.weixin.qq.com/cgi-bin/oa/journal/get_record_list?access_token=");
        if (wxResponse.journaluuid_list.Count > 0)
        {
            foreach (var item in wxResponse.journaluuid_list)
            {
                result = await CheckWeeklyReport(item);
            }
            result.SetSuccess();
            return result;
        }
        if (wxResponse.endflag == 0)
        {
            request.cursor = wxResponse.next_cursor;
            await UpdateDataBaseWeeklyReport(request);
        }

        return result;
    }

    public async Task<CommonResponse> CheckWeeklyReport(string journaluuid)
    {
        var result = new CommonResponse();

        var sqlbuilder = new SqlBuilder();
        var sql = @"SELECT *
                    FROM weekly_report WHERE 1 = 1 AND is_deleted = 0 ";
        sqlbuilder.Add(" AND journal_uuid = @Journaluuid ", "@Journaluuid", journaluuid);

        var entity = await _dateBaseService.QueryFirstOrDefaultAsync<WeeklyReportEntity>(sql, sqlbuilder, 0, "QywxDocument");

        if (entity != null)//更新
        {
            result = await GetRecordDetail(journaluuid, 1, entity.Id);
        }
        else
        {
            result = await GetRecordDetail(journaluuid, 0, string.Empty);//新增
        }

        return result;
    }
    /// <summary>
    /// 获取记录详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<CommonResponse> GetRecordDetail(string id, int type, string reportId)//0新增，1修改
    {
        var result = new CommonResponse();

        var content1 = new
        {
            journaluuid = id
        };
        var temp = JsonConvert.SerializeObject(content1);

        var content = new StringContent(
            JsonConvert.SerializeObject(content1),
            System.Text.Encoding.UTF8,
            "application/json");

        var wxResponse = await _qywxBaseService.QywxCommonPost<WeeklyReportResponse>(content, "https://qyapi.weixin.qq.com/cgi-bin/oa/journal/get_record_detail?access_token=");
        
        if(wxResponse.info.template_id != "C4c8F1X2Pidcs8GLm5adG6VHCM18CNjpdEAP19VeZ")
        {
            result.SetSuccess();
            return result;
        }

        if (wxResponse.info.apply_data.contents.Count > 0 && wxResponse.info.apply_data.contents[0].value.children.Count > 0)
        {
            var department = await GetDepartment(wxResponse.info.submitter.userid);
            var reportEntity = new WeeklyReportEntity()
            {
                Id = Guid.NewGuid().ToString(),
                Journal_Uuid = wxResponse.info.journal_uuid,
                Template_Id = wxResponse.info.template_id,
                Template_Name = wxResponse.info.template_name,
                Report_Time = ToolHelper.ConvertSecondsToDateTimeString(wxResponse.info.report_time),
                Submitter_Userid = wxResponse.info.submitter.userid,
                Tips_Content = wxResponse.info.apply_data.contents[1].title[0].text,
                Shop = department.shop,
                Department = department.department,
                Created_On = DateTime.Now,
                Is_Deleted = 0
            };

            if (type == 1)
            {
                reportEntity.Id = reportId;//如果修改，那么使用存在的id
            }

            result = await SaveWeeklyReportToDateBase(reportEntity, type);

            if (!result.Success)
            {
                return result;
            }

            var sendContentRequest = new InsertDocumentRequest<QywxDocumentWeeklyReport>()
            {
                docid = "dcafxAZKGBCcu7zoH6pgHRTkZbVIGR2sGoeTSHnFjnlorGNqrhTKBZ0rkIfM_J_hWayaKGRY7CzYOUC7TnFl9yLw",
                sheet_id = "t4NDh9",
                key_type = "CELL_VALUE_KEY_TYPE_FIELD_ID",
                records = new List<InsertDocumentRecords<QywxDocumentWeeklyReport>>()
            };

            foreach (var item in wxResponse.info.apply_data.contents[0].value.children)//这个方法用来组装详情
            {
                var reportContentEntity = new WeeklyReportContentEntity()
                {
                    Report_Id = reportEntity.Id,
                    Is_Deleted = 0,
                };


                foreach (var listItem in item.list)
                {
                    reportContentEntity.Id = Guid.NewGuid().ToString();

                    if (listItem.title[0].text == "服务对象")
                    {
                        reportContentEntity.Service_Object = listItem.value.text;
                    }
                    if (listItem.title[0].text == "目标")
                    {
                        reportContentEntity.Target = listItem.value.text;
                    }
                    if (listItem.title[0].text == "行动措施")
                    {
                        reportContentEntity.Action_Measure = listItem.value.text;
                    }
                    if (listItem.title[0].text == "结果呈现")
                    {
                        reportContentEntity.Result_Presentation = listItem.value.text;
                    }
                    if (listItem.title[0].text == "类型")
                    {
                        reportContentEntity.Type_Key = listItem.value.selector.options[0].key;
                        reportContentEntity.Type_Value = listItem.value.selector.options[0].value[0].text;
                    }
                    if (listItem.title[0].text == "协作人")
                    {
                        reportContentEntity.Collaborator = listItem.value.text;
                    }
                }
                result = await SaveWeeklyReportContentToDateBase(reportContentEntity, 0);

                var temp1 = new QywxDocumentWeeklyReport()
                {
                    fkmhUA = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = reportEntity.Journal_Uuid ?? string.Empty } },
                    fiqJSY = ToolHelper.ConvertDateTimeStringToMilliseconds(reportEntity.Report_Time) ?? string.Empty,
                    f5n3aE = new List<InsertDocumentCommonUserType>() { new InsertDocumentCommonUserType { user_id = reportEntity.Submitter_Userid } },
                    fayszY = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = reportContentEntity.Type_Value ?? string.Empty } },
                    fTXDCx = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = reportContentEntity.Service_Object ?? string.Empty } },
                    fULNor = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = reportContentEntity.Target ?? string.Empty } },
                    fqevOw = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = reportContentEntity.Action_Measure ?? string.Empty } },
                    f7nSXH = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = reportContentEntity.Result_Presentation ?? string.Empty } },
                    fBebYR = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = reportContentEntity.Collaborator ?? string.Empty } },
                    fW6BKN = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = reportEntity.Shop ?? string.Empty } },
                    fWl98Y = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = reportEntity.Department ?? string.Empty } },
                };
                var temp2 = new InsertDocumentRecords<QywxDocumentWeeklyReport>()
                {
                    values = temp1
                };
                sendContentRequest.records.Add(temp2);
            }
            result = await _netDocumentService.InsertDocument<QywxDocumentWeeklyReport>(sendContentRequest);
            return result;
        }

        return result;
    }

    /// <summary>
    /// 保存基础数据到数据库
    /// </summary>
    /// <param name="request"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public async Task<CommonResponse> SaveWeeklyReportToDateBase(WeeklyReportEntity request, int type)//0新增，1修改
    {
        var result = new CommonResponse();
        var sql = string.Empty;
        var sqlbuilder = new SqlBuilder();
        sqlbuilder.Add("", "@Id", request.Id);
        sqlbuilder.Add("", "@IsDeleted", request.Is_Deleted);
        sqlbuilder.Add("", "@JournalUuid", request.Journal_Uuid);
        sqlbuilder.Add("", "@TemplateName", request.Template_Name);
        sqlbuilder.Add("", "@TemplateId", request.Template_Id);
        sqlbuilder.Add("", "@ReportTime", request.Report_Time);
        sqlbuilder.Add("", "@SubmitterUserid", request.Submitter_Userid);
        sqlbuilder.Add("", "@TipsContent", request.Tips_Content);
        sqlbuilder.Add("", "@Shop", request.Shop);
        sqlbuilder.Add("", "@Department", request.Department);

        if (type == 0)
        {
            sql = @$"INSERT INTO weekly_report (
    id, 
    created_on, 
    is_deleted, 
    journal_uuid, 
    template_name,
    template_id,
    report_time,
    submitter_userid,
    tips_content,
    shop,
    department
) VALUES (
    @Id, 
    @CreatedOn, 
    @IsDeleted, 
    @JournalUuid, 
    @TemplateName,
    @TemplateId,
    @ReportTime,
    @SubmitterUserid,
    @TipsContent,
    @Shop,
    @Department
);";
            sqlbuilder.Add("", "@CreatedOn", request.Created_On);
        }
        else
        {
            sql = $@"UPDATE weekly_report
SET 
    modified_on = @ModifiedOn,        
    is_deleted = 0,        
    journal_uuid = @JournalUuid,    
    template_name = @TemplateName,
    template_id = @TemplateId,
    report_time = @ReportTime,
    submitter_userid = @SubmitterUserid,
    tips_content = @TipsContent,
    shop = @Shop,
    department = @Department
WHERE 
    id = @Id;";
            sqlbuilder.Add("", "@ModifiedOn", request.Modified_On);

            var tempSql = $@"UPDATE weekly_report_content 
SET 
    is_deleted = 1
WHERE report_id = @ReportId;";

            var tempSqlBuilder = new SqlBuilder();
            tempSqlBuilder.Add("", "@ReportId", request.Id);
            await _dateBaseService.ExecuteAsync(tempSql, tempSqlBuilder, 0, "QywxDocument");

        }

        result = await _dateBaseService.ExecuteAsync(sql, sqlbuilder, 0, "QywxDocument");

        result = await CheckAndSendContentToDocument(request.Submitter_Userid, request.Report_Time);

        return result;
    }

    public async Task<GetDepartMentResponse> GetDepartment(string userid)
    {
        var result = new GetDepartMentResponse();

        var sql = string.Empty;
        var sqlBuilder = new SqlBuilder();

        sql = @"SELECT iws.iren_shi_id FROM ihr_wechat_staff iws
LEFT JOIN qy_wx_openuserid_to_userid qwotu ON iws.wechat_id = qwotu.open_userid WHERE 1 = 1 ";

        sqlBuilder.Add(" AND qwotu.userid = @UserId ", "@UserId", userid);

        var irsId = await _dateBaseService.QueryFirstOrDefaultAsync<string>(sql, sqlBuilder, 0, "QywxUser");

        var irsSql = string.Empty;
        var irsSqlBuilder = new SqlBuilder();

        irsSql = @"SELECT 
  SUBSTRING_INDEX(SUBSTRING_INDEX(full_department_name, '/', 2), '/', -1) AS shop,
  SUBSTRING_INDEX(SUBSTRING_INDEX(full_department_name, '/', 3), '/', -1) AS department
FROM i_staff_v2 WHERE 1 = 1 ";

        irsSqlBuilder.Add(" AND id = @UserId ", "@UserId", irsId);

        result = await _dateBaseService.QueryFirstOrDefaultAsync<GetDepartMentResponse>(irsSql, irsSqlBuilder, 0, "IhrData");

        return result;
    }

    /// <summary>
    /// 保存详细数据到数据库
    /// </summary>
    /// <param name="request"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public async Task<CommonResponse> SaveWeeklyReportContentToDateBase(WeeklyReportContentEntity request, int type)//0新增，1修改
    {
        var result = new CommonResponse();
        var sql = string.Empty;
        var sqlbuilder = new SqlBuilder();
        sqlbuilder.Add("", "@Id", request.Id);
        sqlbuilder.Add("", "@IsDeleted", request.Is_Deleted);
        sqlbuilder.Add("", "@ReportId", request.Report_Id);
        sqlbuilder.Add("", "@ServiceObject", request.Service_Object);
        sqlbuilder.Add("", "@Target", request.Target);
        sqlbuilder.Add("", "@ActionMeasure", request.Action_Measure);
        sqlbuilder.Add("", "@ResultPresentation", request.Result_Presentation);
        sqlbuilder.Add("", "@TypeKey", request.Type_Key);
        sqlbuilder.Add("", "@TypeValue", request.Type_Value);
        sqlbuilder.Add("", "@Collaborator", request.Collaborator);

        if (type == 0)
        {
            sql = @$"INSERT INTO weekly_report_content (
    id, 
    created_on, 
    is_deleted, 
    report_id, 
    service_object,
    target,
    action_measure,
    result_presentation,
    type_key,
    type_value,
    collaborator
) VALUES (
    @Id, 
    @CreatedOn, 
    @IsDeleted, 
    @ReportId, 
    @ServiceObject,
    @Target,
    @ActionMeasure,
    @ResultPresentation,
    @TypeKey,
    @TypeValue,
    @Collaborator
);";
            sqlbuilder.Add("", "@CreatedOn", DateTime.Now);
        }
        else
        {
            sql = $@"UPDATE weekly_report_content 
SET 
    modified_on = @ModifiedOn, 
    is_deleted = 0, 
    report_id = @ReportId, 
    service_object = @ServiceObject,
    target = @Target,
    action_measure = @ActionMeasure,
    result_presentation = @ResultPresentation,
    type_key = @TypeKey,
    type_value = @TypeValue,
    collaborator = @Collaborator
WHERE id = @Id;";
            sqlbuilder.Add("", "@ModifiedOn", DateTime.Now);
        }

        result = await _dateBaseService.ExecuteAsync(sql, sqlbuilder, 0, "QywxDocument");
        return result;
    }
    #endregion

    #region 推送汇报统计表格-》在线文档

    /// <summary>
    /// 检查是否存在此人的统计数据并推送
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="date"></param>
    /// <returns></returns>
    public async Task<CommonResponse> CheckAndSendContentToDocument(string userId, DateTime date)
    {
        var result = new CommonResponse();

        var sendRequestContent = await BuildStaticContent(userId, date);

        var sqlbuilder = new SqlBuilder();
        var sql = @"SELECT *
                    FROM weekly_report_static WHERE 1 = 1 AND is_deleted = 0 ";
        sqlbuilder.Add(" AND user_id = @UserId ", "@UserId", userId);
        sqlbuilder.Add(" AND date = @Date ", "@Date", date.ToString("yyyyMM"));

        var entity = await _dateBaseService.QueryFirstOrDefaultAsync<WeeklyReportStaticEntity>(sql, sqlbuilder, 0, "QywxDocument");

        if (entity != null)//直接拿返回值的id进行
        {
            var reco = new UpdateDocumentRecords<QywxDocumentSortedFieldReport>()
            {
                record_id = entity.Record_Id,
                values = sendRequestContent.records[0].values
            };

            var updateRequest = new UpdateDocumentRequest<QywxDocumentSortedFieldReport>()
            {
                docid = sendRequestContent.docid,
                sheet_id = sendRequestContent.sheet_id,
                key_type = sendRequestContent.key_type,
                records = new List<UpdateDocumentRecords<QywxDocumentSortedFieldReport>>()
            };

            updateRequest.records.Add(reco);

            result = await _netDocumentService.UpdateDocument<QywxDocumentSortedFieldReport>(updateRequest);
        }
        else//新建一条record并记录返回值
        {
            result = await _netDocumentService.InsertDocument<QywxDocumentSortedFieldReport>(sendRequestContent);
            List<RecordItem> records = (List<RecordItem>)result.data;
            foreach (var item in records)
            {
                result = await SaveWeeklyReportStaticToDateBase(userId,date, item.RecordId);
            }
        }

        return result;
    }

    /// <summary>
    /// 保存records数据到数据库
    /// </summary>
    /// <param name="request"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public async Task<CommonResponse> SaveWeeklyReportStaticToDateBase(string userId, DateTime date,string recordId)//0新增，1修改
    {
        var result = new CommonResponse();
        var sql = string.Empty;
        var sqlbuilder = new SqlBuilder();
        sqlbuilder.Add("", "@Id", Guid.NewGuid().ToString());
        sqlbuilder.Add("", "@UserId", userId);
        sqlbuilder.Add("", "@Data", date.ToString("yyyyMM"));
        sqlbuilder.Add("", "@RecordId", recordId);
        sqlbuilder.Add("", "@CreatedOn", DateTime.Now);
        sqlbuilder.Add("", "@IsDeleted", 0);

        sql = @$"INSERT INTO weekly_report_static (
    id, 
    user_id, 
    date, 
    record_id, 
    created_on,
    is_deleted
) VALUES (
    @Id, 
    @UserId, 
    @Data, 
    @RecordId, 
    @CreatedOn,
    @IsDeleted
);";

        result = await _dateBaseService.ExecuteAsync(sql, sqlbuilder, 0, "QywxDocument");

        return result;
    }

    /// <summary>
    /// 获取需要推送的更新数据
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="date"></param>
    /// <returns></returns>
    public async Task<InsertDocumentRequest<QywxDocumentSortedFieldReport>> BuildStaticContent(string userId, DateTime date)
    {
        var res = new InsertDocumentRequest<QywxDocumentSortedFieldReport>()
        {
            docid = "dcafxAZKGBCcu7zoH6pgHRTkZbVIGR2sGoeTSHnFjnlorGNqrhTKBZ0rkIfM_J_hWayaKGRY7CzYOUC7TnFl9yLw",
            sheet_id = "q979lj",
            key_type = "CELL_VALUE_KEY_TYPE_FIELD_ID",
            records = new List<InsertDocumentRecords<QywxDocumentSortedFieldReport>>()
        };
        var sql = string.Empty;
        var sqlbuilder = new SqlBuilder();
        sql = @"SELECT 
  DISTINCT 
  submitter_userid AS userId,
  shop,
  department,
  DATE(report_time) AS date  -- 提取纯日期，自动忽略时分秒
FROM 
  weekly_report WHERE 1 = 1 ";
        sqlbuilder.Add("AND submitter_userid = @UserId", "@UserId", userId);

        var month = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).Date;
        var monthString = month.ToString("yyyyMM");

        sqlbuilder.Add("AND report_time > @DateTime", "@DateTime", month);

        var sqlRes = await _dateBaseService.QueryAsync<WeeklyStaticResponse>(sql, sqlbuilder, 0, "QywxDocument");

        var temp1 = new QywxDocumentSortedFieldReport()
        {
            ftQMc5 = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = monthString ?? string.Empty } },
            fxem5P = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = sqlRes[0].shop ?? string.Empty } },
            fJArGI = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = sqlRes[0].department ?? string.Empty } },
            ftk5Tx = new List<InsertDocumentCommonUserType>() { new InsertDocumentCommonUserType { user_id = userId } },
        };

        foreach (var item in sqlRes)
        {
            // 确保 date 有值再判断（避免空引用异常）
            if (!item.date.HasValue) continue;

            var day = item.date.Value.Day;
            var textObj = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = "是" ?? string.Empty } };

            if (day == 1) { temp1.fd37rp = textObj; }
            if (day == 2) { temp1.ftJjPr = textObj; }
            if (day == 3) { temp1.fWXjKR = textObj; }
            if (day == 4) { temp1.fLb9sr = textObj; }
            if (day == 5) { temp1.fjIYdZ = textObj; }
            if (day == 6) { temp1.fRi5tZ = textObj; }
            if (day == 7) { temp1.f5e8yr = textObj; }
            if (day == 8) { temp1.fefY4X = textObj; }
            if (day == 9) { temp1.fS1mWV = textObj; }
            if (day == 10) { temp1.f2T9gG = textObj; }
            if (day == 11) { temp1.fcF993 = textObj; }
            if (day == 12) { temp1.fRYj9Y = textObj; }
            if (day == 13) { temp1.f4bVeS = textObj; }
            if (day == 14) { temp1.fneP9x = textObj; }
            if (day == 15) { temp1.f5z40Q = textObj; }
            if (day == 16) { temp1.fYrizH = textObj; }
            if (day == 17) { temp1.fLMQ55 = textObj; }
            if (day == 18) { temp1.fX0Suu = textObj; }
            if (day == 19) { temp1.fAxcCW = textObj; }
            if (day == 20) { temp1.fQVDYu = textObj; }
            if (day == 21) { temp1.f2Lu7N = textObj; }
            if (day == 22) { temp1.fNdF7G = textObj; }
            if (day == 23) { temp1.fYcta6 = textObj; }
            if (day == 24) { temp1.fjhzit = textObj; }
            if (day == 25) { temp1.fAs63i = textObj; }
            if (day == 26) { temp1.fkZJcs = textObj; }
            if (day == 27) { temp1.fx7B4t = textObj; }
            if (day == 28) { temp1.fyBN7n = textObj; }
            if (day == 29) { temp1.foDs1I = textObj; }
            if (day == 30) { temp1.fJyrL9 = textObj; }
            if (day == 31) { temp1.fW2rwY = textObj; }
        }

        var temp2 = new InsertDocumentRecords<QywxDocumentSortedFieldReport>()
        {
            values = temp1
        };
        res.records.Add(temp2);
        return res;
    }

    #endregion
}